﻿using Alipay.EasySDK.Factory;
using Alipay.EasySDK.Kernel;
using Alipay.EasySDK.Kernel.Util;
using Alipay.EasySDK.Payment.Page.Models;

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using ProsonUser.DomainOrderInfo;
using ProsonUser.Pay;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Book.Pay
{
    public class ALiPayAppService : ApplicationService, IALiPayAppService
    {
        private IRepository<OrderInfo, int> _order;
        private readonly IHttpContextAccessor _contextAccessor;
        public ALiPayAppService(IHttpContextAccessor contextAccessor, IRepository<OrderInfo, int> orderInfos)
        {
            _contextAccessor = contextAccessor;
            _order = orderInfos;
        }
        [HttpGet]
        //直接测试用地址,记得改订单信息. https://localhost:44341/api/app/a-li-pay/pay?Subject=test1&outTradeNo=111111111112&totalAmount=500
        public async void Pay(PayDto dto)
        {
            #region 1. 设置参数（全局只需设置一次）
            var config = new Config()
            {
                Protocol = "https",
                GatewayHost = "openapi.alipaydev.com",//"openapi.alipay.com",沙箱
                SignType = "RSA2",
                AppId = "2021000118636016",
                //请填写您的应用私钥
                MerchantPrivateKey = "MIIEpAIBAAKCAQEAp3RM8M2Smz+/QDmCJzw2cbCOtCt4fVRYv2mS/2VATFfd4WvrX+zSBgmC2EtcGYlVMr2VNW3QsDwVeJmqisoPUrHSgWqAxzH2jVMVh8femql2Xf78H3POazArTkIGuZ6lHXqkXR9lGh2YHvQtKixJ5DxAEyw8U5V7KGKK5CufITH5lIcIngu7DnY1k3FZ17Hd+OKnzi14D4E/rwurtl/PBNfozISvub0bIfBbiHEdhOt6pXjFoTUjy3zu85lSSo7ViNIks+cBdAKCh7T2qVmazobsF0qZhG1l1702BQVyA8CGW873PO8U8+ty4KSoUgb0wjsDDJ1aoAnbt/w+vFGAgwIDAQABAoIBAAfaEzWDXil7brtTNwAh+aeREM/v7eFqkBLBn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Y1Y6CoZreuqhG8HzmgjJ0gHmB1UUQ4LoXtZs403KrSfBlCnca5S+Pkkw1F4Hhd0nzoUvnytOzOz9YpN+JrRJ8l1TGyTmmxfkSgqa62pQ==",
                //支付宝公钥
                AlipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkAC2MZqGGSGg64rc7/SqJA8T7k1XLO1OnXTTFZrx/yQwC6EQ+Rn1O5KDmjzW3sYdXGJrpkSxNu+Fz8Bxyb80fzch0lMSI1HxitZfvm9ja1f5o15/V6gdtHUz/ZCcRjoB79ZQ9Am/j5vr8wiThWIAtTm9SMk4zKc3wBWuiX3TYA1lcEbH+5bSaLlwC1imq7Rct442BQ5jK2WsYcVEfbkecLbMx6yFnSm6bbP3TQT3KZlG+ra2J+OFhwY9qKUT1KqMZHWbktEFgPd6hN4X9Xmz3YV18r08NrBAt2T5IJxFUFG5L7ek5KIlC+I7x5/L0vmHmQQPhTXg4oaCJC/arcN9aQIDAQAB",
                //异步回调地址
                NotifyUrl = "https://localhost:44347/api/app/a-li-pay/notify-url",
            };
            Factory.SetOptions(config);
            #endregion


            try
            {
                // 2. 发起API调用（以创建当面付收款二维码为例）
                //TODO:实训标题和订单号及金额是从dto中取得                                                                      
                AlipayTradePagePayResponse response = Factory.Payment.Page().Pay(dto.Subject, dto.outTradeNo, dto.totalAmount, "https://localhost:44347/api/app/a-li-pay/return-url");
                // 3. 处理响应或异常
                if (ResponseChecker.Success(response))
                {
                    //把返回的html直接变成网页显示
                    var data = Encoding.UTF8.GetBytes(response.Body);
                    _contextAccessor.HttpContext.Response.ContentType = "text/html";
                    await _contextAccessor.HttpContext.Response.Body.WriteAsync(data.AsMemory(0, data.Length));
                }
                else
                {
                    Console.WriteLine("调用失败，原因：" + response.Body);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("调用遭遇异常，原因：" + ex.Message);


            }
        }
        [HttpGet]
        public string ReturnUrl(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //if()先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update

                var list = _order.Where(s => s.Id.ToString().Equals(dto.out_trade_no)).FirstOrDefault();
                list.OrderInfoState = 20;
                _order.UpdateAsync(list);

                return "success";
            }
            return "";
        }
        [HttpGet]
        public string NotifyUrl(PayReturnDto dto)
        {
            var parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(dto));
            if (Factory.Payment.Common().VerifyNotify(parameters) == true)
            {
                //TODO:更新此条订单状态为已付款,并修改付款成功时间,加商户网站唯一订单号字段更新进去,后续如果需要查询或退款,再调支付宝接口时需要传入商户网站唯一订单号
                //先查一下这条订单,是不是已经改过已付款或更往后的状态了,注意不要重复更新,因为支付宝可能会多次回调
                //update
                //再循环返回库存
                //update


                return "success";
            }
            return "";
        }
    }
}
